package com.course.model.util;


import com.course.model.exception.ValidatorException;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;

/**
 * @PROJECT_NAME: course
 * @DESCRIPTION: 统一校验前端参数的工具
 * @Author: 涂玄武
 * @DATE: 2021/4/12 10:59
 */
public class ValidatorUtil {

    //TODO:统一校验前端传递过来的参数
    public static void checkResult(BindingResult result){
        StringBuilder sb=new StringBuilder("");
        if (result.hasErrors()){
            //java8 steam api
            result.getAllErrors().forEach(error -> sb.append(error.getDefaultMessage()).append("\n"));
        }
        if (org.apache.commons.lang3.StringUtils.isNotBlank(sb.toString())){
            throw new ValidatorException(sb.toString());
        }
    }

    /**
     * 空校验（null or ""）
     */
    public static void require(Object str, String fieldName) {
        if (StringUtils.isEmpty(str)) {
            throw new ValidatorException(fieldName + "不能为空");
        }
    }

    /**
     * 长度校验
     */
    public static void length(String str, String fieldName, int min, int max) {
        if (StringUtils.isEmpty(str)) {
            return;
        }
        int length = 0;
        if (!StringUtils.isEmpty(str)) {
            length = str.length();
        }
        if (length < min || length > max) {
            throw new ValidatorException(fieldName + "长度" + min + "~" + max + "位");
        }
    }
}

































